package com.yl.message.service.impl.sendNoticeImpl

import com.alibaba.fastjson.JSONObject
import com.tencentcloudapi.common.Sign
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.message.service.MessageService
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.NameValuePair
import org.apache.commons.httpclient.URI
import org.apache.commons.httpclient.methods.GetMethod
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.URLDecoder

class VolcanoSmsMessageServiceImpl(): MessageService {

    companion object {
        /**
         *  应用地址
         */
        private const val url = "sms.volcengineapi.com/SendSms"
        private val log = LoggerFactory.getLogger(SmsMessageServiceImpl::class.java)!!
    }

    override fun send(config: JSONObject, userId: Long, msgBody: JSONObject): ResponseBody {
        val smsAccount = config.getString("smsAccount") ?: return returnError(
            ErrorCode.SEND_MESSAGE_ERROR,
            "短信推送账号未设置") // 账号

        val sign = config.getString("sign") ?:  return returnError(
            ErrorCode.SEND_MESSAGE_ERROR,
            "短信签名未设置")// 密码

        //模板
        val templateID = msgBody.getString("templateID")

        val templateParam = msgBody.getJSONObject("templateParam")
        val msg = msgBody.getString("message")
        val tag = ""
        try {
            val mobilePhone = config.getString("mobilePhone") ?:  return returnError(
                ErrorCode.SEND_MESSAGE_ERROR,
                "未找到手机号码")// 密码
            val returnString = batchSends(url,smsAccount, sign,templateID,templateParam.toString(), mobilePhone, msg)
            // TODO 处理返回值,参见HTTP协议文档
            log.info("短信发送成功", returnString)
        } catch (e: Exception) {
            // TODO 处理异常
            log.error("发送消息出现异常。", e)
            return returnError(
                ErrorCode.SEND_MESSAGE_ERROR,
                "发送消息出现异常")// 密码

        }
        return returnSuccess()
    }

    private fun batchSends(sendUrl: String, smsAccount: String, sign: String, templateID:String,templateParam:String,
                           phoneNumbers: String,
                           tag: String): String {
        var result: String? = ""
        val client = HttpClient()
        val method = GetMethod()
        try {
            val base = URI(sendUrl, false)
            method.uri = URI(base, "send", false)
            method.setQueryString(
                arrayOf(
                    NameValuePair("SmsAccount", smsAccount),
                    NameValuePair("Sign",sign),
                    NameValuePair("TemplateID", templateID),
                    NameValuePair("TemplateParam", templateParam),
                    NameValuePair("phoneNumbers", phoneNumbers),
                    NameValuePair("Tag", "hhkq")
                )
            )
            val reqResult: Int = client.executeMethod(method)
            if (reqResult == HttpStatus.SC_OK) {
                val `in`: InputStream = method.responseBodyAsStream
                val baas = ByteArrayOutputStream()
                val buffer = ByteArray(1024)
                var len: Int
                while (`in`.read(buffer).also { len = it } != -1) {
                    baas.write(buffer, 0, len)
                }
                result = URLDecoder.decode(baas.toString(), "UTF-8")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            method.releaseConnection()
        }
        return result!!
    }
}